-- Copyright 2011-2012 Benjamin Leppard

-- This file is part of Picasa Metadata Import Into Lightroom.

-- Picasa Metadata Import Into Lightroom is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.

-- Picasa Metadata Import Into Lightroom is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-- GNU General Public License for more details.

-- You should have received a copy of the GNU General Public License
-- along with Picasa Metadata Import Into Lightroom.  If not, see <http://www.gnu.org/licenses/>.

local LrProgressScope = import 'LrProgressScope'
local LrApplication = import 'LrApplication'
local LrPathUtils = import 'LrPathUtils'
local LrProgressScope = import 'LrProgressScope'

require "Logger"
require "Global"

-- local Require = require 'Require'.path ("../../../progs/debugscript.lrdevplugin")
-- local Debug = require 'Debug'.init ()
pluginRequire 'common/libraries/strict.lua'

-- local TableShow = pluginRequire      "common/libraries/table_show.lua"
local List = pluginRequire           "common/libraries/List.lua"
-- local Profiler = pluginRequire       "common/Profiler.lua"
-- local toString = TablePrint.to_string

local catalog = LrApplication.activeCatalog()

local PicasaMetadata = {}

function PicasaMetadata.picasaSection(headerFileName)
	return "Contacts" == headerFileName or "contacts" == headerFileName or 
	"Picasa" == headerFileName or "picasa" == headerFileName or 
	"encoding" == headerFileName
end

function PicasaMetadata.parsePicasaIni(picasaIniPath)

--	Logger:log("parsePicasaIni: " .. picasaIniPath)
	
	local photoPathToPropertyToValue = {}
	
	local picasaIniDirectory = LrPathUtils.parent(picasaIniPath)

	local picasaIni = io.open(picasaIniPath, "r")
	if picasaIni then 
		
		local photoPath = nil
		local propertyToValue = {}
		
		for line in picasaIni:lines() do 
			local headerFileName = line:match('%s*%[(.*)%]%s*')
			
			if headerFileName then
			
				if photoPath then
					photoPathToPropertyToValue[photoPath] = propertyToValue
--					Logger:log("parsePicasaIni: File: " .. photoPath)
				end
			
				local newPhotoPath = nil
				if PicasaMetadata.picasaSection(headerFileName) then
					newPhotoPath = headerFileName
				else
					newPhotoPath = LrPathUtils.child(picasaIniDirectory, headerFileName)
				end
				newPhotoPath = newPhotoPath:lower()
				
				photoPath = newPhotoPath
				propertyToValue = {}
			else 
				local name, value = line:match('%s*(.-)=(.*)%s*')
				name:lower()
				propertyToValue[name] = value
--				Logger:log("parsePicasaIni: Property Name: " .. name .. ", value: " .. value)
			end
		end
		
		picasaIni:close() 
	else
		Logger:log("ManualUpdate: Picasa.Ini didn't exist for: " .. picasaIniPath)
	end
	
	return photoPathToPropertyToValue
end

function PicasaMetadata.getPropertiesFromPhotos(context, photos)
	local picasaIniFileNameToPhotoPathToPropertyToValue = {}
	local photoPathToPhoto = {}

	if nil ~= photos then

		local progressScope = LrProgressScope {
			title = 'Retrieving Picasa Metadata'
--	        functionContext = context,
		}
		local numberOfSelectedPhotols = #photos
		progressScope:setPortionComplete( 0, numberOfSelectedPhotols )
		
		local paths = catalog:batchGetRawMetadata(photos, {'path'})

		for photoNumber, photo in ipairs( photos ) do

			--local photoPath = photo.path--local photoPath = photo:getRawMetadata( 'path' )

			local photoPath = paths[photo].path
			photoPathToPhoto[photoPath:lower()] = photo

			local picasaIniDirectory = LrPathUtils.parent(photoPath)
			local picasaIniPath = LrPathUtils.child(picasaIniDirectory, "Picasa.Ini")
			local photoPathToPropertyToValue = picasaIniFileNameToPhotoPathToPropertyToValue[picasaIniPath]

			if not photoPathToPropertyToValue then
				picasaIniFileNameToPhotoPathToPropertyToValue[picasaIniPath] = PicasaMetadata.parsePicasaIni(picasaIniPath)
			end

			progressScope:setPortionComplete( photoNumber, numberOfSelectedPhotols )
		end

		progressScope:done()
	end
	
	return {
		PhotoPathToPhoto = photoPathToPhoto,
		PicasaIniFileNameToPhotoPathToPropertyToValue = picasaIniFileNameToPhotoPathToPropertyToValue
	}
end


function PicasaMetadata.setProperties(context, picasaIniFileNameToPhotoPathToPropertyToValue, photoPathToPhoto)
	local progressScopeSettingMetadata = LrProgressScope {
		title = 'Setting Picasa Metadata',
        functionContext = context,
	}
	
	local setProperties  = function ()	
		
		Logger:log("setProperties: Setting Properties")
		local photoNumber = 0
		
--		Logger:log("setProperties: picasaIniFileNameToPhotoPathToPropertyToValue: " .. TableShow.show(picasaIniFileNameToPhotoPathToPropertyToValue))
		for picasaIniFileName, photoPathToPropertyToValue in pairs(picasaIniFileNameToPhotoPathToPropertyToValue) do
--			Logger:log("setProperties: Setting picasaIniFileName: " .. picasaIniFileName .. ", photoPathToPropertyToValue: " .. toString(photoPathToPropertyToValue))
			for photoPath, propertyToValue in pairs(photoPathToPropertyToValue) do
--				Logger:log("setProperties: Setting photoPath: " .. photoPath .. ", propertyToValue: " .. toString(propertyToValue))

				if PicasaMetadata.picasaSection(photoPath) then
					--elseif "name" == property then
					--		-- Need to handle
				else
					for property, value in pairs(propertyToValue) do
					
	--					Logger:log("setProperties: Setting Property: " .. property .. ", value: " .. value)
						if "star" == property then
							value:lower()
							local star = ("yes" == value)
							
							local starString
							if star then
								starString = "true"
							else
								starString = "false"
							end

--							Logger:log("ManualUpdate: Star: " .. starString)
							--local photo = photoPathToPhoto[photoPath]
							--photo:setPropertyForPlugin( _PLUGIN, "star", starString)
						elseif "crop" == property then
	--						Logger:log("Crop property found.")
							handleCropProperty(value)
						elseif "rotate" == property then
							
--							Logger:log("photoPathToPhoto: " .. toString(photoPathToPhoto))
--							local photo = photoPathToPhoto[photoPath]
--							local developSettings = photo:getDevelopSettings()
--							Logger:log("Orientation: " .. developSettings["Orientation"])
							
							-- Not possible given the current API.
							-- Need to handle
						elseif "faces" == property then
							-- Not yet
						elseif "filter" == property then
							-- Not yet
						elseif "filters" == property then
							-- Not yet
						elseif "fix" == property then
							-- Not yet
						elseif "bw" == property then
							-- Not yet
						elseif "flipped" == property then
							-- Not yet
						elseif "date" == property then
							-- Don't do anything for date
						elseif "moddate" == property then
							-- Don't do anything for moddate
						elseif "backuphash" == property then
							-- Don't do anything for backuphash
						elseif "height" == property then
							-- Don't do anything for height
						elseif "width" == property then
							-- Don't do anything for width
						elseif "redo" == property then
							-- Don't do anything for redo
						elseif "textactive" == property then
							-- Don't do anything for textactive
						elseif "text" == property then
							-- Don't do anything for text
						elseif string.match(property, "IIDLIST_.*") then -- Online Photo ID
							-- Don't do anything for IIDLIST_*
						else
							Logger:log("Unknown Property: Property: " .. property .. ", value: " .. value .. ", File Name: " .. photoPath)
						end
						--photoNumber = photoNumber + 1
						--progressScope:setPortionComplete( photoNumber, numberOfSelectedPhotols )
					end
				end
			end
		end
	end
	
	catalog:withWriteAccessDo("Picasa Metadata Update", setProperties)
	
	progressScopeSettingMetadata:done()
end

return PicasaMetadata